import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:talking/tools/config.dart';

class Account extends StatefulWidget {
  @override
  AccountPage createState() => AccountPage();
}

class AccountPage extends State<Account> with TickerProviderStateMixin {
  File? image;
  var nicknameController=TextEditingController();

  @override
  void dispose() {
    nicknameController.dispose();
    super.dispose();
  }
  late var email=null;
  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero,()  async {
      SharedPreferences sp =await SharedPreferences.getInstance();
      email=sp.getString("email")!;
      Dio dio=Dio();
      var res=(await dio.get("${Constant.BASE_URL}user/getNickname/?email=${email}")).data.toString();
      setState(() {
        if(res=="该用户未注册"){
          nicknameController.text="";
        }else{
          nicknameController.text=res;
        }
      });
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("编辑资料"),
      ),
      body: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
                gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                  Colors.lightBlueAccent.withOpacity(0.3),
                  Colors.lightBlue.withOpacity(0.3),
                  Colors.blue.withOpacity(0.3),
                ])),
          ),
          Column(
            children: [
              Padding(
                padding: EdgeInsets.only(top: 50),
                child: InkWell(
                  child: CircleAvatar(
                    radius: 40,
                    backgroundColor: Colors.grey,
                    backgroundImage:circleAvatar(),
                  ),
                  onTap: () async {
                    ImagePicker().pickImage(source: ImageSource.gallery).then((value) {
                      ImageCropper.cropImage(sourcePath: value!.path, aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1)).then((value) {
                        setState(() {
                          image = value;
                        });
                      });
                    });
                  },
                ),
              ),
              Padding(padding: EdgeInsets.all(20), child: Text("点击头像进行更换")),
              Padding(
                padding: EdgeInsets.only(bottom: 20),
                child: TextField(
                  controller: nicknameController,
                  autofocus: true,
                  textInputAction: TextInputAction.next,
                  decoration: InputDecoration(
                    labelText: "昵称",
                    prefixIcon: const Icon(Icons.people),
                    hintText: "请输入昵称",
                    hintStyle: TextStyle(
                      color: Colors.grey[500]
                    ),
                  ),
                ),
              ),
              Row(
                children: [
                  ElevatedButton(
                    onPressed: () async {
                      Dio dio = new Dio();
                      SharedPreferences sp =await SharedPreferences.getInstance();
                      if(image!=null){
                        await dio.post("${Constant.BASE_URL}user/updateIcon/?email=${sp.getString("email")}",data:FormData.fromMap({"file":await MultipartFile.fromFile(image!.path)}));
                        image=null;
                      }
                      if(nicknameController.text!=""){
                        await dio.get("${Constant.BASE_URL}user/updateNickname/?email=${sp.getString("email")}&nickname=${nicknameController.text}");
                      }
                      Navigator.pop(context);
                    },
                    child: const Text("保存"),
                    style: ButtonStyle(
                      minimumSize: MaterialStateProperty.all(Size(150, 40)),
                    ),
                  ),
                  ElevatedButton(
                    onPressed: () async {},
                    child: const Text("修该密码"),
                    style: ButtonStyle(
                      minimumSize: MaterialStateProperty.all(Size(150, 40)),
                    ),
                  ),
                ],
                mainAxisAlignment: MainAxisAlignment.spaceAround,
              ),
            ],
          ),
        ],
      ),
    );
  }
  circleAvatar()  {
    if(image==null){
      if(email!=null){
        return NetworkImage("${Constant.BASE_URL}files/icon/${email}.png?t=${Constant.getTimeStamp()}");
      }else{
        return null;
      }
    }else{
      return FileImage(File(image!.path));
    }
  }
}
